﻿using JESAI.Redis.Abstracts;
using JESAI.Redis.Abstracts.RedisClients;
using JESAI.Redis.Pools;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace JESAI.Redis.RedisClients
{
    internal class RedisClientPool : IRedisClientPool
    {
        public DateTime LastUseTime { get; set; }
        private static IRedisClientFactory _redisClientFactory;
        public static async Task<IObjectInstancePool<IRedisClient>> BuildAsync(IConnectionBuilder connectionBuilder)
        {
            var pool = new ObjectInstancePool<IRedisClient>(connectionBuilder.PoolSize, connectionBuilder.MaxPoolSize, connectionBuilder.TryGetRetryCount, connectionBuilder.IdleTime);
            _redisClientFactory = await RedisClientFactory.BuildAsync(connectionBuilder);

            pool.SetCreateNewObjectFunc(CreateNewRedisClient);


            pool.Start();
            return pool;
        }

        private async static Task<IRedisClient> CreateNewRedisClient(Action<IRedisClient> action, CancellationToken token)
        {
            var res = await _redisClientFactory.GetAsync(Return, token);
            return res;
        }

        private static void Return(IRedisClient redisClient)
        {

        }

        public void Dispose()
        {

        }
    }
}
